<?php
	/** Classe permettant d'exporter les données au format XML 
	 * @author sebastian mosser
	 */

class XmlExporter {

	private $_season;     ///<! Saison traitée
	
	/** Table volatiles de donnés **/
	
	private $_categories; ///<! Table des catégories d'équipe
	private $_teams;      ///<! Table des équipes

	private $_players;    ///<! Table des Joueurs
	private $_directors;  ///<! Table des Dirigeants
	private $_coachs;     ///<! Table des Entraineurs

	private $_matches;    ///<! Table des Matches
	
	private $_news;       ///<! Table des News	

	/** Données binaires **/	
	private $_pictures;   ///<! Table des images
	private $_pics;       ///<! Table des pics


	private $_XML_FILES;
	private $_PATH;


	/** fonction statique publie appelée par le client **/
	
	public static function run($seasonId) {
		$oldSeason = Login::seasonChoosen(False);
		Login::seasonChoosen($seasonId);
		$exporter = new XmlExporter($seasonId);
		$exporter->process();
		Login::seasonChoosen($oldSeason);
	}


	/** FONCTIONS D'AJOUT a desctination des entitées visitées **/

	/** Insertions de données depuis le pattern visiteur implanté**/
	public function insertData($mnemonic,$key,$value) {
		switch($mnemonic) {
			case "category":
				$this->_categories[$key] = $value;
				break;
			case "team":
				$this->_teams[$key] = $value;
				break;
			case "player":
				$this->_players[$key] = $value;
				break;
			case "director":
				$this->_directors[$key] = $value;
				break;
			case "coach":
				$this->_coachs[$key] = $value;
				break;
			case "matche":
				$this->_matches[$key] = $value;
				break;
			case "news":
				$this->_news[$key] = $value;
				break;
		}
	}

	public function insertPics($file) {
		$this->_pics[$file] = True;
	}
	
	public function insertPicture($large, $small) {
		$this->_pictures[$large] = $small;
	}
	
	
	private function __construct($sId) {
		
		$this->_season = $sId;
		$aSeason = Season::read($sId);
		$label = str_replace(" ","",$aSeason->displayShort());
		
	 	$this->_PATH = BALLOON_FS_PATH . "xmlExportation/".$label."/";
	 	
		$this->_categories = array() ; $this->_teams = array();
		$this->_players = array()    ; $this->_directors = array();
		$this->_coachs = array()     ; $this->_matches = array();
		$this->_pictures = array()   ; $this->_pics = array();
		$this->_news = array()       ;
		$this->initFileArray();
	}
	
	private function initFileArray() {
		$this->_XML_FILES = array();
		$this->_XML_FILES["categories"] = $this->_PATH . "categories.xml";
		$this->_XML_FILES["teams"]      = $this->_PATH . "teams.xml";
		$this->_XML_FILES["players"]    = $this->_PATH . "players.xml";
		$this->_XML_FILES["directors"]  = $this->_PATH . "directors.xml";
		$this->_XML_FILES["coachs"]     = $this->_PATH . "coachs.xml";
		$this->_XML_FILES["matches"]    = $this->_PATH . "matches.xml";
		$this->_XML_FILES["pictures"]   = $this->_PATH . "pictures.xml";
		$this->_XML_FILES["pics"]       = $this->_PATH . "pics.xml";
		$this->_XML_FILES["news"]       = $this->_PATH . "news.xml";
	}
	
	// fonctionne par code de retour : 
	// --> -2 : le fichier demandé n'est pas une clé de la table des fichiers
	// --> -1 : le fichier demandé n'existe pas
	// --> 0  : Egalité de contenu
	// --> 1  : Différence de contenu
	public function xmlEquality($string, $fileName) {
		if (! array_key_exists($fileName,$this->_XML_FILES))
			return -2;
		if (! file_exists($this->_XML_FILES[$fileName]))
			return -1;
		$content =file_get_contents($this->_XML_FILES[$fileName]);
		$ans = ($content == $string ? 0 : 1);
		return $ans;
	}
	
	private function process() {
		// On parcourt les catégories d'équipes
		$myTeamCats = TeamCategory::lookFor($this->_season);
		while (($row = Database::assoc($myTeamCats)) != False)
			$this->visitTeamCategory($row["id"]);
		
		// Maintenant, les équipes
		$myTeams = Team::lookFor($this->_season);
		while(($row = Database::assoc($myTeams)) != False)
			$this->visitTeam($row["id"]);
		
		
		// Nos tables d'associations sont maintenant a jour
		// On écrit juste ce qu'il faut : 
		$this->synchronizeTablesToFiles();
	}
	
	private function synchronize($xmlRoot,$xmlArray,$fileMnemonic) {
		$xml = $this->dump2file($xmlRoot,$xmlArray);
		$ans =  $this->xmlEquality($xml,$fileMnemonic) ;
		echo "\n##   - ${fileMnemonic}      \t:: " . ($ans == 0 ? "Unchanged" : "Updated");
		if ($ans != 0) {
			$f = new File($this->_XML_FILES[$fileMnemonic]);
			$f->open(File::WRITE); $f->write($xml); $f->close();
		}
	}
	
	private function synchronizeTablestoFiles() {
		// Traitement des fichiers textes
		$this->synchronize("team_categories",$this->_categories,"categories");
		$this->synchronize("teams",$this->_teams,"teams");
		$this->synchronize("players",$this->_players,"players");
		$this->synchronize("directors",$this->_directors,"directors");
		$this->synchronize("coachs",$this->_coachs,"coachs");
		$this->synchronize("matches",$this->_matches,"matches");

		// Traitement des données binaires
		
		// Traitement des 'pics' des joueurs
		$tmp = array();
		foreach($this->_pics as $k => $v) {
			// Gestion du coté binaire de la chose 
			$fileName = basename($k);
			if (file_exists($this->_PATH."pics/".$fileName)) {
				$old = file_get_contents($this->_PATH."pics/".$fileName);
				$new = file_get_contents($k);
				if ($old != $new)
					copy($k,$this->_PATH."pics/".$fileName);
			} else {
				if (file_exists($k))
					copy($k,$this->_PATH."pics/".$fileName);
			}
			$dest = "pics/".$fileName;
			// Maj du xml de liaison
			$tmp[] = "	<pic id=\"${k}\">${dest}</pic>";
		}
		$this->synchronize("pics",$tmp,"pics");
		
		// Traitement des images 'larges' & 'small'
		$tmp = array();
		foreach($this->_pictures as $k => $v) {
			// Gestion du coté binaire de la chose 
			$largeName = basename($k);
			$smallName = basename($v);
			if (file_exists($this->_PATH."pictures/".$largeName)) {
				$old = file_get_contents($this->_PATH."pictures/".$largeName);
				$new = file_get_contents($k);
				if ($old != $new) {
					copy($k,$this->_PATH."pictures/".$largeName);
					copy($v,$this->_PATH."pictures/".$smallName);
				}
			} else {
				if (file_exists($k)) {
					copy($k,$this->_PATH."pictures/".$largeName);
					copy($v,$this->_PATH."pictures/".$smallName);
				}
			}
			$small = "pictures/".$smallName;
			$large = "pictures/".$largeName;
			// Maj du xml de liaison
			$tmp[] = <<<EOS
	<picture id="${k}">
		<small>${small}</small>
		<large>${large}</large>
	</picture>
EOS;
		}
		$this->synchronize("pictures",$tmp,"pictures");
		
		
	}
	
	// Renvoie une string qui correpond au fichier complet a partir du tableau
	private function dump2file($xmlRootElement,$array) {
		$content = "";
		foreach ($array as $k => $v) 
			$content .= $v . "\n";
		$ans = <<<EOS
<?xml version="1.0" encoding="UTF-8"?>
<${xmlRootElement} xmlns="http://ogcnice-association.fr/Balloon" >
${content}
</${xmlRootElement}>
EOS;
		return str_replace("&","&amp;",$ans);
	}
	
	/** PATTERN DE VISITE DES DIFFERENTS ELEMENTS **/
	
	public function visitTeamCategory($catId) {
		try {
			$myCat = TeamCategory::read($catId);
			$myCat->xmlExport($this);
		} catch (Exception $e) { return; }
	}
	
	public function visitTeam($teamId) {
		try {
			$myTeam = Team::read($teamId);
			$myTeam->xmlExport($this);
		} catch (Exception $e) { return; }
	}
	
	public function visitMember($memberId,$type) {
		try {
			if ($type == "player" and array_key_exists($memberId,$this->_players))
				return;
			if ($type == "director" and array_key_exists($memberId,$this->_directors))
				return;
			if ($type == "coach" and array_key_exists($memberId,$this->_coachs))
				return;
			$aMember = Member::read($memberId);
			$aMember->xmlExport($this,$type);
		} catch (Exception $e) { return; }
	}
	
	public function visitMatche($matcheId) {
		try {
			$aMatche = Matche::read($matcheId);
			$aMatche->xmlExport($this);
		} catch (Exception $e) { return; }
	}
	

}

?>